// 定义删除房屋的id和index
let house_id = ''
let house_index = ''

Page({
  data: {
    dialogVisible: false,
  },

  swipeClose(ev) {
    const { position, instance } = ev.detail

    if (position === 'right') {
      // 显示 Dialog 对话框
      this.setData({
        dialogVisible: true,
      })
      // 获取删除房屋的id和index
      house_id = ev.mark.house_id
      house_index = ev.mark.house_index
      // swiper-cell 滑块关闭
      instance.close()
    }
  },
  // 确认删除
  dialogClose(ev) {
    ev.detail === 'confirm' && this.deleteHouse()
  },
  // 去往房屋详情页面
  goDetail(ev) {
    wx.navigateTo({
      url: '/house_pkg/pages/detail/index?id=' + ev.mark.house_id,
    })
  },

  addHouse() {
    wx.navigateTo({
      url: '/house_pkg/pages/locate/index',
    })
  },
  onShow() {
    // 获取房屋列表
    this.getHouseList()
  },
  //获取房屋列表
  async getHouseList() {
    // 请求数据接口
    const { code, data: houseList } = await wx.http.get('/room')
    // 检测接口返回的结果
    if (code !== 10000) return wx.utils.toast()
    // 渲染数据
    this.setData({ houseList })
  },
  // 删除房屋的接口
  async deleteHouse() {
    const { code } = await wx.http.delete('/room/' + house_id)
    if (code !== 10000) return wx.utils.toast('删除房屋失败')
    // 更新房屋数据
    this.data.houseList.splice(house_index, 1)
    console.log(this.data.houseList)
    // 只有通过setData改变数据才能更行视图
    this.setData({
      houseList: this.data.houseList,
      isEmpty: this.data.houseList.length === 0,
    })
  },
})
